/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logger;

import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author Kvest
 */
public class Logger {
    private static final String LOG_RMS = "logDB";
    
    private static Logger instance;
    private static final Object lock = new Object();
    
    public static Logger getInstance() {
        synchronized(lock) {
            if (instance == null) {
                instance = new Logger();
            }
        }
        
        return instance;
    }
    
    private Logger() {}
    
    public synchronized void log(String text) {
System.out.println("log[" + text + "]");        
        try
        {
            RecordStore recordStore = RecordStore.openRecordStore(LOG_RMS, true);
            byte[] res = text.getBytes();
            recordStore.addRecord(res,0,res.length);
            recordStore.closeRecordStore();
        }catch(RecordStoreException rse){};
    }
    
    public synchronized String getLog() {
        byte[] temp;
        Vector items = new Vector();
        try
        {
            RecordStore recordStore = RecordStore.openRecordStore(LOG_RMS, true);
            RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
            if (re.numRecords()!=0)
            {
                re.rebuild();
                while (re.hasNextElement())
                {
                    int id = re.nextRecordId();
                    try
                    {
                        temp = recordStore.getRecord(id);
                        items.addElement(new String(temp));
                    }catch(Exception e){}
                }
            }
            recordStore.closeRecordStore();
            re.destroy();
        }catch(RecordStoreException rse){};
        
        StringBuffer sb = new StringBuffer();
        for (int i = items.size() - 1; i >= 0; --i) {
            sb.append(items.elementAt(i));
            sb.append("\n");
        }
        
        return sb.toString();
    }
    
    public synchronized void clear() {
        try
        {
             RecordStore.deleteRecordStore(LOG_RMS);
        }catch(Exception e){}
    }
}
